import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { Row, Col } from 'antd'

import LoginForm from '../../components/LoginForm'
import ChangeLanguage from '../../components/ChangeLanguage'
import { noticeSuccess, noticeError } from '../../utils/notice'
import styles from './login.less'

class Login extends React.Component {
  getChildContext() {
    return {
      currentLanguage: this.props.currentLanguage
    }
  }

  get loginFormProps() {
    return {
      userName: this.props.userName,
      phoneNumber: this.props.phoneNumber,
      loading: this.props.loading,
      onLogin: this.props.onLogin
    }
  }

  get changeLanguageProps() {
    return {
      currentLanguage: this.props.currentLanguage,
      supportLanguages: this.props.supportLanguages
    }
  }

  render() {
    return (
      <Row type="flex" justify="center" align="middle" className={styles.normal}>
        <ChangeLanguage {...this.changeLanguageProps} />
        <Col xs={22} sm={12} md={8} lg={8} xl={8}>
          <LoginForm {...this.loginFormProps} />
        </Col>
      </Row>
    )
  }
}

Login.childContextTypes = {
  currentLanguage: PropTypes.string
}

Login.defaultProps = {
  loading: false
}

Login.propTypes = {
  userName: PropTypes.string.isRequired,
  phoneNumber: PropTypes.string.isRequired,
  loading: PropTypes.bool,
  currentLanguage: PropTypes.string.isRequired,
  supportLanguages: PropTypes.array.isRequired,
  onLogin: PropTypes.func.isRequired
}

export const mapStateToProps = state => ({
  userName: state.login.userName,
  phoneNumber: state.login.phoneNumber,
  loading: state.loading.models.login,
  currentLanguage: state.app.currentLanguage,
  supportLanguages: state.app.supportLanguages
})

const mapDispatchToProps = dispatch => ({
  onLogin: (userName, phoneNumber) => dispatch({
    type: 'login/login',
    payload: {
      userName,
      phoneNumber
    },
    onSuccess: msg => noticeSuccess(msg),
    onError: (code, msg) => noticeError(code, msg)
  })
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)
